package Kuaishou;

import static java.util.stream.Collectors.toList;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import com.google.common.collect.Lists;

import lombok.Data;

/**
 * @author leiwenkang <leiwenkang@kuaishou.com>
 * Created on 2021-04-20
 */
public class Test37FlatMap {
    public static void main(String[] args) {
        List<User> uList = Lists.newArrayList();
        User u1 = new User();
        u1.setAddr("a1;a2;a3;a4;a5");

        User u2 = new User();
        u2.setAddr("b1;b2;b3;b4;b5");

        uList.add(u1);
        uList.add(u2);

        List<String> addrList = uList.stream().map(x -> x.getAddr()).flatMap(x -> Arrays.stream(x.split(";")))
                .collect(toList());
        //或者
        List<String> ridStrList = uList.stream().map(x -> x.getAddr()).map(x -> x.split(";")).flatMap(Arrays::stream)
                .collect(toList());
        System.out.println(addrList);
        System.out.println(ridStrList);

        //降维  给 定 单 词 列 表[“Hello”,“World”] ，要返回列表 [“H”,“e”,“l”, “o”,“W”,“r”,“d”] 。
        String[] words = new String[]{"Hello","World"};
        List<String[]> a = Arrays.stream(words)
                .map(word -> word.split(""))
                .distinct()
                .collect(toList());
        System.out.println(a);

        List<String> b = Arrays.stream(words)
                .map(word -> word.split(""))
                .flatMap(Arrays::stream)
                .distinct()
                .collect(toList());
        System.out.println(b);

        //升维 给定两个数字列表，如何返回所有的数对呢？例如，给定列表[1, 2, 3]和列表[3, 4]，应该返回[(1, 3), (1, 4), (2, 3), (2, 4), (3, 3), (3, 4)]。
        List<Integer> numbers1 = Arrays.asList(1, 2, 3);
        List<Integer> numbers2 = Arrays.asList(3, 4);
        // flatMap升维度
        List<int[]> pairs = numbers1.stream().flatMap(x -> numbers2.stream().map(y -> new int[] { x, y }))
                .collect(Collectors.toList());
        for (int[] pair : pairs) {
            System.out.println(Arrays.toString(pair));
        }


    }
}

@Data
class User {
    private String addr;
}


